"Useful functions for manipulating strings. In particular those in CSV files."

# No imports needed as no regular expressions are used

# Errors
class ParserError(Exception):
    pass

# Define functions
def stripEnd(line, whitespace=' '):
	'''if it's string, remove right blanks
		if it's char list,remove right blank
	'''
	if type(line) == type(''):
		return line.rstrip()
	else:
		return list(''.join(line).rstrip())

def stripStart(line, whitespace=' '):
	'''if it's string, remove left blanks
		if it's char list,remove left blank
	'''
	if type(line) == type(''):
		return line.lstrip()
	else:
		return list(''.join(line).lstrip())

def stripBoth(line, whitespace=' '):
	'''removing starting and ending spaces
	'''
	return stripStart(stripEnd(line,whitespace),whitespace)
	
def splitKeepQuotedValues(string, seperater=' ', quote="'"):
    p = string.split(quote)
    params = []
    for x in range(len(p)):
        if x%2: # ie odd
            params.append(p[x])
        else:
            for param in p[x].split(seperater):
                if param:
                    params.append(param)
    return params

def parseCSV(input,	separater=',', quote='"', linebreak='\n', whitespace=' ', swap={}):
	'''parse input string into list of string list
	"""" => "
	" "  => space
	","  => ,
	"\n" => \n
	'''
	if not input:
		return [[],]
	input=input.replace('""""','<:quote:>') #replace quote
	input=input.replace('" "','<:space:>') #replace quote
	input=input.replace('"\n"','<:newline:>') #replace newline
	input=input.replace('","','<:comma:>') #replace comma

	res=[]
	for line in input.split('\n')[:-1]:
		tmp=[]
		for i in line.split(','):
			if '<:quote:>' in i:
				tmp.append(i.replace('<:quote:>','"'))
			elif '<:space:>' in i:
				tmp.append(i.replace('<:space:>',' '))
			elif '<:comma:>' in i:
				tmp.append(i.replace('<:comma:>',','))
			elif '<:newline:>' in i:
				tmp.append(i.replace('<:newline:>','\n'))
			else:
				tmp.append(i)
		res.append(tmp)
	return res
	#pass
            
def buildCSV(lines, separater=',', quote='"', linebreak='\n', whitespace=' '):
	'''generate writable string from list of string list
	>>> s.buildCSV([['a','b','"',' '],['\n']])
		'a,b,""""," "\n"\n"\n'
	'''
	result = ''
	for line in lines:
		l=[]
		for item in line:
			if quote in item:
				l.append(quote+item.replace(quote,quote+quote)+quote)
			elif separater in item or linebreak in item or whitespace in item:
				l.append(quote+item+quote)
			else:
				l.append(item)
		#xxx bad performance here		
		result += separater.join(l)+linebreak
	return result	


def smartSplit(term, separater=',', quote='"', linebreak='\n', whitespace=' ', swap={}):
    return parseCSV(term+linebreak, separater, quote, linebreak,  whitespace, swap)[0]
    
def splitPlainList( tables, whitespace=' ', separater=','):
    table = tables.replace(whitespace,'')
    tables = table.split(separater)
    return tables

# Test
if __name__ == '__main__':
    print smartSplit("'test1', NULL, h ", quote="'", swap={'NULL':None})
